package cn.stazxr.component;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Package: cn.stazxr.component
 *
 * @Author: stazxr
 * @Create: 2023/12/11
 * @Version: v1.0
 **/
public class IOProgressBar {
    public static void main(String[] args) {
        JFrame frame = new JFrame("我是标题");
        frame.setBounds(500, 300, 500, 300);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JProgressBar bar = new JProgressBar();
        bar.setMaximum(1000);
        bar.setBounds(20, 50, 300, 15);
        frame.add(bar);

        JButton button = new JButton("点击开始"); // 点击按钮开始拷贝
        button.setBounds(20, 100, 100, 30);
        button.addActionListener(event -> new Thread(() -> {
            System.out.println("已开始");
            long start =System.currentTimeMillis();
            File file = new File("jdk-1.8.0.zip");
            try (FileInputStream in = new FileInputStream(file);
                 FileOutputStream out = new FileOutputStream("jdk-copy.zip")) {
                long size = file.length(), current = 0;
                int length;
                byte[] buffer = new byte[32]; // 32b
                while ((length = in.read(buffer)) != -1) {
                    current += length;
                    out.write(buffer, 0, length);
                    int value = (int) (current * 1000.0 / size);
                    bar.setValue(value);
                    bar.repaint();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            long endTime = System.currentTimeMillis() - start;
            System.out.println("已结束");
            System.out.println("拷贝时间：" + endTime + "ms");
        }).start());
        frame.add(button);

        frame.setVisible(true);
    }
}
